/*
 * 基础弹框类
 * 用于输出提示数据
 * @author：黄
 */
'use strict'
// 此处使用elementui的弹框
import Vue from 'vue'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
class Layer {
  constructor () {
    this.loading = null
  }

  /*
   * 成功提示
   */
  success (info) {
    Element.Message.success({
      showClose: true,
      message: info,
      type: 'success'
    })
  }

  /*
   * 错误提示
   */
  error (info) {
    Element.Message.error({
      showClose: true,
      message: info,
      type: 'error'
    })
  }

  /*
   * 全局loading
   * 开启
   */
  openLoading () {
    this.loading = Element.Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }

  /*
   * 全局loading
   * 关闭
   */
  closeLoading () {
    this.loading.close()
  }

  /*
   * confirm
   */
  confirm (str, fun) {
    Element.MessageBox.confirm(str, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      fun()
    }).catch(() => {})
  }

  /*
   * prompt
   */
  prompt (tips, fun) {
    Element.MessageBox.prompt(tips, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(({ value }) => {
      // 和后端交互
      if (value) fun(value)
    }).catch(() => {})
  }

  /*
   * 复杂弹窗页面
   */
  openDialog (obj, currentView, data, width) {
    return new Promise((resolve, reject) => {
      const Dialog = Vue.extend({
        template: `<el-dialog :visible.sync="dialogTableVisible" :width="width">
          <component v-bind:is="currentView" v-on:increment="incrementTotal" :getdatas="getdatas"></component>
        </el-dialog>`,
        props: ['currentView', 'getdatas'],
        watch: {
          dialogTableVisible: function (v) {
            if (!v) this.$el.parentNode.removeChild(this.$el)
          }
        },
        data () {
          return {
            dialogTableVisible: false,
            width: ''
          }
        }
      })
      let store = obj.$store
      let d = new Dialog({
        propsData: {
          currentView: currentView,
          getdatas: data
        },
        data: {
          dialogTableVisible: true,
          width: width || ''
        },
        methods: {
          incrementTotal (data) {
            this.dialogTableVisible = false
            resolve(data)
          }
        },
        store
      })
      d.$mount()
      setTimeout(function () {
        document.body.appendChild(d.$el)
      })
    }).catch((e) => {
      console.log(e)
    })
  }

  /*
   * 关闭复杂弹窗
   */
  closeDialog (obj, data) {
    obj.$emit('increment', data)
  }

  gets (obj) {
    return obj.$attrs.getdatas
  }
}

export default new Layer()
